package com.qst.crop.controller;

import com.qst.crop.Api.Sample;
import com.qst.crop.common.ResultPhtot;
import com.qst.crop.entity.User;
import com.qst.crop.service.PhotoService;
import com.qst.crop.service.UserService;
import com.qst.crop.utils.BASE64;
import org.json.JSONException;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;

@RestController
@CrossOrigin
public class PhotoController{
    @Autowired
    PhotoService photoService;

    @PostMapping("/werk/Login")
    @ResponseBody
    public ResultPhtot werkLogin(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException, JSONException {

        // 传入可选参数调用接口
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("max_face_num", "3");
        options.put("match_threshold", "80");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("max_user_num", "3");

        String image = getimages(file, request);//得到前端传过来的照片存储的地址
        String imageType = "BASE64";
        String groupIdList = "group1";

        // 人脸搜索 M:N 识别
        JSONObject res = Sample.getTAipFace().multiSearch(image, imageType, groupIdList, options);
        System.out.println(res.toString(2));

        int id;
        User user=null;
        try {
            id= res.getJSONObject("result").getJSONArray("face_list")
                    .getJSONObject(0).getJSONArray("user_list")
                    .getJSONObject(0).getInt("user_id");
            user= photoService.getById(id);
            //发送请求 okhttpclient发 username pwd /user/login
        }catch (Exception e){
            System.err.println("登入失败，图像不合格");
        }

        return ResultPhtot.ok().data("data",user);
    }

    @PostMapping("/face/registered")
    @ResponseBody
    public ResultPhtot registered(@RequestParam("file")  MultipartFile file
            ,HttpServletRequest request,
                                  @RequestParam("id") String id
    ) throws IOException, JSONException {

        // 传入可选参数调用接口
        HashMap<String, String> options = new HashMap<String, String>();
        options.put("user_info", "user's info");
        options.put("quality_control", "NORMAL");
        options.put("liveness_control", "NONE");
        options.put("action_type", "REPLACE");

        String image = getimages(file,request);
        String imageType = "BASE64";
        String groupId = "group1";
        String userId = id;


        // 人脸注册
        JSONObject res = Sample.getTAipFace().addUser(image, imageType, groupId, userId, options);
        System.out.println(res.toString(2));

        return ResultPhtot.ok().data("data",res.get("result").toString());
    }


    public String getimages(MultipartFile file, HttpServletRequest request) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile headerImage = multipartRequest.getFile("file");

        if (headerImage == null) {
            System.out.println("您还没有选择图片");
        }

        String fileName = headerImage.getOriginalFilename();

        //根据当前时间生成文件名
        fileName = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date()) + "." + fileName;
        //System.out.println(fileName);
        // 确定文件存放的路径
        File dest = new File("E:\\photo" + "/" + fileName);
        try {
            // 存储文件
            headerImage.transferTo(dest);
        } catch (IOException e) {
            throw new RuntimeException("上传文件失败,服务器发生异常!", e);
        }

        return BASE64.encodeImgageToBase64(dest);
    }
}

